<!-- 标准管理->跟投管控标准->新增/编辑/查看 -->
<template>
    <div class="followUpControl">
        <el-breadcrumb separator="/" class="bread-title">
			<el-breadcrumb-item :to="{ path: '/followUpControl' }">跟投管控标准</el-breadcrumb-item>
			<el-breadcrumb-item>{{pageType}}</el-breadcrumb-item>
		</el-breadcrumb>
       <el-form ref="typeForm" :rules="rules" :model="typeForm"   >
           <div class="type-item-box">
                <p class="type-item-title">基础信息</p>
                 <el-form-item label="标准名称：" prop="name" >
                        <el-input style="max-width:550px" v-if="typeStatus !='view'" v-model.trim="typeForm.name" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.name}}</span>
                 </el-form-item>
                 <el-form-item label="项目类型：" prop="lineType">
                       <template v-if="typeStatus !='view'">
                            <el-radio v-model="typeForm.lineType" :disabled="inputDisabled" :label="1">内部项目</el-radio>
                            <el-radio v-model="typeForm.lineType" :disabled="inputDisabled" :label="0">外部项目</el-radio>
                        </template>
                        <span v-else>{{typeForm.lineType|typeFilter}}</span>
                 </el-form-item>
                 <el-form-item label="合作模式：" prop="lineCollaborat">
                        <el-select v-if="typeStatus !='view'" v-model.trim="typeForm.lineCollaborat" :disabled="inputDisabled"  placeholder="请选择合作模式">
                             <el-option 
                                v-for="(type,typeIdx) in modalOptions" 
                                :key="typeIdx" 
                                :label="type.label" 
                                :value="type.value"></el-option>
                        </el-select>
                         <span v-else>{{typeForm.lineCollaborat|modalFilter}}</span>
                </el-form-item>
           </div>
            <!-- 循环表单 -->
            <div class="type-item-box" >
                <template v-if="typeStatus !='view'">
                    <p class="type-item-title">请设置跟投额度比例区间</p>
                    <div class="for-form-box"  :class="{'error-bg':calcScale(index) || moneyError} " v-for="(item,index) in typeForm.moneys" :key="index">
                        <div class="item-box line">
                            <el-form-item  :prop="`moneys.${index}.inMini`" :rules="rules.yuan" >
                                <el-input  v-model.trim="item.inMini" @blur="calcMoneySize()" autocomplete="off"></el-input>
                            </el-form-item>
                            <div class="unit-box">元 ~</div>
                            <el-form-item :prop="`moneys.${index}`" :rules="rules.yuan2">
                                    <el-input   v-model.trim="item.inMax" @blur="calcMoneySize()"  autocomplete="off"></el-input>
                            </el-form-item>
                            <div class="unit-box">元 </div>
                            <div class="unit-box">
                                <el-button @click="changeFormBox('dele',index)" v-if="index!=0" type="text">删除</el-button>
                            </div>
                        </div>
                        <div class="item-box"  v-for="(opc,pocIdx) in item.rows"  :key="index+'-'+pocIdx">
                            <el-form-item :prop="`moneys.${index}.rows.${pocIdx}.inRooted`" :rules="rules.bodyType">
                                <el-select  v-model.trim="opc.inRooted" @change="onslChange(index,pocIdx,opc.inRooted)"  placeholder="请选择跟投主体类型">
                                    <el-option 
                                    v-for="(type,typeIdx) in bodyOptions" 
                                    :key="typeIdx" 
                                    :label="type.label" 
                                    :value="type.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item >
                                <el-input :disabled="true" style='width:calc(100% - 80px)'  v-model.trim="opc.inBole" autocomplete="off"></el-input>
                                <el-button type="primary" :disabled="(!opc.inRooted && opc.inRooted!==0) || opc.inRooted===3" @click="selectInbole(index,pocIdx,opc.inRooted)">选择</el-button>
                            </el-form-item>
                            <el-form-item  :prop="`moneys.${index}.rows.${pocIdx}.inLeaf`" :rules="rules.cycle">
                                <el-input v-model.trim="opc.inLeaf" @blur="calcScale(index)" autocomplete="off"></el-input>
                            </el-form-item>
                            <div class="unit-box">%</div>
                            <div class="unit-box">
                                <el-button v-if="pocIdx==0" type="text" @click="changeFormItem('add',index,pocIdx)">增加</el-button>
                                <el-button @click="changeFormItem('dele',index,pocIdx)" v-else type="text">删除</el-button>
                            </div>
                        </div>
                        <div v-show="calcScale(index) || moneyError" class="error-text">{{moneyError?'金额区间不能重复且不能相同':'同一区间内比例之和必须为100'}}</div>
                    </div>
                </template>
                <template v-else>
                    <p class="type-item-title">跟投额度比例</p>
                    <scale-table  :tableData="typeForm.moneys"></scale-table>
                </template>
                
           </div>
           <el-button v-if="typeStatus !='view'" @click="changeFormBox('add')" type="primary">增加区间</el-button>
            <div style="padding:10px 0">
               <el-form-item label="超出标准允许发起审批流程：" prop="orexceed">
                       <template v-if="typeStatus !='view'">
                            <el-radio v-model="typeForm.orexceed" :label="1">是</el-radio>
                            <el-radio v-model="typeForm.orexceed" :label="0">否</el-radio>
                        </template>
                        <span v-else>{{typeForm.orexceed?"是":"否"}}</span>
                 </el-form-item>
           </div>
        </el-form>
       <p v-if="typeStatus !='view'" style="text-align:center">
            <el-button type="primary"  @click="loadApproval">发起审批</el-button>
            <el-button type="primary" v-if="typeStatus =='add'" @click="addSave(0)">保存</el-button>
            <el-button type="primary" v-if="typeStatus =='edit'" @click="editSave(0)">保存</el-button>
            <el-button type="primary"  @click="back">取消</el-button>
        </p>
        <!-- 审核记录 -> 详情页面显示 -->
        <template  v-else>
            <audit-table :tableData='auditData'></audit-table>
            <p style="text-align:center"> 
                 <el-button type="primary"  @click="back">关闭</el-button>
            </p>
           
        </template>
        <el-dialog
            :title="inboleTitle"
            :visible.sync="inboleVisible"
            width="70%"
            >
            <inbole-table :type="inboleType" :form="searchForm" @selectChange='selectChange'></inbole-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="inboleVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectInboleData" >确 定</el-button>
            </span>
        </el-dialog>
        
    </div>
    
</template>

<script>
import api from '@/api/apiPath'
import auditTable from '../common/auditTable' //审核记录表
import scaleTable from './scaleTable'
import inBoleTAble from './inBoleTable'
export default {
    components: {
        'audit-table':auditTable,
        'scale-table':scaleTable,
        'inbole-table':inBoleTAble
    },
    computed:{
        inputDisabled(){
            return this.typeForm.examineStatus == 2;
        },
    },
	data () {
		return {
            prevMini:'',
            prevMax:'',
            inboleData:'',//记录选中的数据
            seleteInboleIdx:{//记录当前纤选择主体名称idx位置
                outIdx:'',
                thisIdx:'',
            },
            inboleType:'',//记录当前选择的主体类型
            inboleTitle:'',//选择框标题
            inboleVisible:false,
            modalOptions:[
                {label:"保证金模式",value:4},
                {label:"包销模式",value:0},
            ],
            bodyOptions:[
                {label:"内部员工",value:3},
                {label:"渠道/经纪",value:1},
                {label:"开发商",value:2},
                {label:"内部法人",value:0},
            ],
            moneyError:false,//检测金额区间错误
            scaleError:false,//检测区间错误
            auditData:[],//操作记录表数据
            searchForm:{
                name:''
            },
          
            typeForm:{
                moneys:[
                    {
                        inMini:'',
                        inMax:'',
                        rows:[
                            {
                                inRooted:'',
                                inBole:'',
                                inLeaf:'',
                                address:'',
                                inBoleId:'',
                                inBoleSort:'',
                                inBoleTaxpayer:'',
                                phone:'',
                                postalcode:'',
                            },
                        ]
                    },
                
                ],
                 orexceed:1,
            },
            typeStatus:"",
            pageType:"",
            typeFunction:{//页面状态
                add:()=>{
                    this.pageType = "新增";
                    
                    },
                edit:(id)=>{this.pageType = "编辑";
                    this.loadFromDetail(id);//加载表单信息
                    
                 
                },
                view:(id)=>{ this.pageType = "详情";
                    this.loadFromDetail(id);
                }
            },
            rules:{//验证
               name:[
                    {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if(!value  && value !=0 ) {
                                    return callback(new Error('请输入标准名称'));
                            }
                            if(value.length>20){
                                    return callback(new Error('标准名称长度不能大于20'));
                            }
                            callback();
                        }
                    }
                ],
            
                type: [
                   { required: true, message: '请选择项目类型', trigger: ['blur', 'change']}
                ],
                lineCollaborat: [
                   { required: true, message: '请选择合作模式', trigger: ['blur', 'change']}
                ],
                yuan:[
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            let flatReg = /^\d+(\.\d{0,2})?$/;
                            if(!value && value!==0) return callback(new Error('不可为空'));
                            if(+value>=1000000000) return callback(new Error('超出最大金额'))
                            if(!flatReg.test(value)){
                                    return callback(new Error('格式不正确'));
                            }
                            callback();
                        }
                    }
                ],
                yuan2:[
                    {
                        required: false,
                        validator: (rule, valueObj, callback) => {
                            if(!valueObj.inMax && valueObj.inMax!==0) return callback();
                            let prevValue = +valueObj.inMini;
                            let thisValue = +valueObj.inMax;
                            let flatReg = /^\d+(\.\d{0,2})?$/;
                            if(!flatReg.test(thisValue)){
                                    return callback(new Error('格式不正确'));
                            }
                            if(+thisValue>=1000000000) return callback(new Error('超出最大金额'))
                            if(thisValue<=prevValue) {
                                 return callback(new Error('截止金额不能小于等于初始金额'));
                            }
                            callback();
                        }
                    }
                ],
                bodyType: [
                   { required: true, message: '请选择跟投主体类型 ', trigger: ['blur', 'change']}
                ],
                
                cycle:[
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if(!value && value!==0) return callback(new Error('不可为空'));
                            if(value==0) return callback(new Error('不能为0'));
                            value = +value;
                            let flatReg = /^\d+(\.\d{0,2})?$/;
                            if(!flatReg.test(value)){
                                    return callback(new Error('格式不正确'));
                            }
                            if(value>100) this.typeForm.easyLifeCycle = 100;
                            callback();
                        }
                    }
                ],
                orexceed: [
                   { required: true, message: '请选择是否超出标准允许发起审批流程', trigger: ['blur', 'change']}
                ],
            },
        }
    },

    methods:{
        //选中主体
        selectInboleData(){
            if(!this.inboleData){
                this.$message.error(this.inboleTitle);
                return ;
            }
             let {outIdx,thisIdx} = this.seleteInboleIdx;
             let hasRepeatFlag = this.typeForm.moneys[outIdx].rows.some(row=>{
                 //检测是否有同一主体类型下的同一主体，判断类型id 和主体id
                 return row.inBoleId === this.inboleData.inBoleId && row.inRooted === this.inboleType;
             })
             if(hasRepeatFlag) {
                 this.$message.error('同一区间下不可选取重复主体')
                 return;
             }
             this.$set(this.typeForm.moneys[outIdx].rows,thisIdx,{
                ...this.inboleData,
                inRooted:this.inboleType,
             })
             this.inboleVisible = false;
        },
        //记录选中主体数据
        selectChange(val){
            this.inboleData=val;
        },
        //点击选择
        selectInbole(outIdx,thisIdx,inboleType){
            let inBoleArray = ['内部法人','渠道/经纪','开发商'];
            this.seleteInboleIdx = {outIdx,thisIdx};
            this.inboleType = inboleType;
            this.inboleTitle =`请选择${inBoleArray[inboleType] || ''}`;
            this.inboleVisible = true;
        },
        addSave(status){
            this.$refs.typeForm.validate((valid)=>{
                if(!valid){
                    return
                }
                //计算金额区间和比例之和是否符合
                this.calcMoneySize();
                this.calcAllScale();
                if(this.moneyError || this.scaleError){
                    return 
                }
                let params = {
                    ...this.typeForm,
                    examineStatus:status,
                }
                this.axios.post(api.addfollowUpControl,params).then((res)=>{
                    if(res.data.code==200){
                         let text = ['添加成功','已发起审批']
                        this.$alert(text[status], '提示', {
                                type: 'success',
                                confirmButtonText: '确定',
                                callback: action => {
                                        this.$router.go(-1)
                                    }
                        });
                    }
                }).catch((error)=>{
                        console.log(error)
                })
            })
            
        },
        editSave(status){
            this.$refs.typeForm.validate((valid)=>{
                if(!valid){
                    return
                }
                //计算金额区间和比例之和是否符合
                this.calcMoneySize();
                this.calcAllScale();
                if(this.moneyError || this.scaleError){
                    return 
                }
                let params = {
                     ...this.typeForm,
                    examineStatus:status,
                }
                this.axios.post(api.editfollowUpControl,params).then((res)=>{
                    if(res.data.code==200){
                         let text = ['编辑成功','已发起审批']
                        this.$alert(text[status], '提示', {
                                type: 'success',
                                confirmButtonText: '确定',
                                callback: action => {
                                        this.$router.go(-1);
                                    }
                        });
                    }
                }).catch((error)=>{
                        console.log(error)
                })
            })
        },
        back(){
            this.$router.go(-1);
        },
        //加载当前页面表单详情
        loadFromDetail(id){
            this.axios.post(`${api.followUpControlDetail}`,{id:id}).then(res => {
                if (res.data.code == 200) {
                    this.typeForm = {
                        ...res.data.data.vote,
                        moneys:res.data.data.voteMoneys
                    }
                    this.auditData = res.data.data.voteLogInfo;
                    
                }
            })
        },
        //发起审批
        loadApproval(){
            if(this.typeStatus =='add') this.addSave(1);
            if(this.typeStatus =='edit') this.editSave(1);
        },
        //切换跟投主体带出主体名称
        onslChange(outIdx,thisIdx,value){
            this.typeForm.moneys[outIdx].rows[thisIdx].inBole = '';
        },
        //增删主体
        changeFormItem(type,outIdx,thisIdx){
            let thisFormItem = this.typeForm.moneys[outIdx].rows;
            if(type== 'add'){
                thisFormItem.push( 
                            {
                                inRooted:'',
                                inBole:'',
                                inLeaf:'',
                                address:'',
                                inBoleId:'',
                                inBoleSort:'',
                                inBoleTaxpayer:'',
                                phone:'',
                                postalcode:'',
                            },
                        )
                
            }else{
                thisFormItem.splice(thisIdx,1);
               
            }
            this.calcScale(outIdx);
        },
        //增删item
        changeFormBox(type,thisIdx){
            if(type == 'add'){
                this.typeForm.moneys.push({
                        inMini:'',
                        inMax:'',
                        rows:[
                            {
                                inRooted:'',
                                inLeaf:'',
                                address:'',
                                inBole:'',
                                inBoleId:'',
                                inBoleSort:'',
                                inBoleTaxpayer:'',
                                phone:'',
                                postalcode:'',
                            },
                        ]
                },)
            }else{
                this.typeForm.moneys.splice(thisIdx,1);
                this.calcMoneySize();
            }
        },
        //计算每个分组的比例 100返回true，不到100返回false
        calcScale(idx){
            let rows = this.typeForm.moneys[idx].rows;
            let allScale= 0;
            //检测是否有空值没填，全部有值在做校验
            let flag= rows.some(opc=>{
                return !opc.inLeaf
            })
            if(flag) return ;
            //累加比例
            rows.forEach(opc=>{
                let scale = +opc.inLeaf;
               allScale+=scale;
            })
            //非法值return
            if(!allScale && allScale!=0) return;
            if(allScale!=100){
                return true;
               
            }else{
                return false;
               
            }
        },
        //计算所有区间
        calcAllScale(){
            let all = this.typeForm.moneys;
            this.scaleError = false;
            all.some(({rows},idx)=>{
                let allScale= 0;
                rows.forEach(opc=>{
                let scale = +opc.inLeaf;
                allScale+=scale;
                })
                if(allScale!=100){
                    this.scaleError = true;
                    return true;
                }
            })
        },
        //计算费用区间
        calcMoneySize(){
            let prevMini =null ,prevMax = null;
            let all = this.typeForm.moneys;
            this.moneyError = false;
            all.some(({inMini,inMax},idx)=>{
                if(!inMini) return;
                if(prevMini == null){
                    prevMini = inMini;
                }
                //如果未填最大金额 则赋值未最大数用作判断
                if(!inMax){
                    inMax = Number.MAX_VALUE || 999999999999999;
                } 
                if(inMax != null && prevMax != null && (inMini>=prevMini) && (prevMax>inMini)){
                    //console.log('当前最小值在上个区间内')
                    this.moneyError = true;
                    return 
                }
                if(inMax != null && prevMax != null && (inMax>=prevMini) && (prevMax>=inMax)){
                   // console.log('当前最大值在上个区间内')
                    this.moneyError = true;
                    return 
                }
                if(inMax != null && prevMax != null && (prevMini>=inMini) && (inMax>=prevMax)){
                    //console.log('当前区间包含上个区间')
                    this.moneyError = true;
                    return 
                }
                if( prevMini != inMini){
                    //取最小值
                    prevMini = Math.min(prevMini,inMini)
                }
                if(prevMax == null && inMax){
                    //取最大值
                    prevMax = inMax;
                }
                if(prevMax != null && inMax && (prevMax != inMax)){
                    //取最大值
                    prevMax = Math.max(prevMax,inMax)
                }
            })
        }
	},
	created () {
       let {pageType,insideId} = this.$route.query;
       //更改页面状态（新增/编辑/查看）
       this.typeStatus = pageType;
       this.insideId = insideId;
       //执行该状态init()
       this.typeFunction[pageType](insideId);
    },
	destroyed() {
		
	},
	filters: {
        typeFilter(type){
            let typeArray = ['外部项目','内部项目'];
            return typeArray[type];
        },
        modalFilter(code){
           return {4:"保证金模式",0:"包销模式"}[code];
        }
	}
}

</script>

<style lang="stylus" >
.followUpControl{
    p{
        margin:0;
        padding:20px 0;
    }
    .type-item-title{
        font-size:18px;
        color:#303133;
        font-weight :700;
        border-bottom: 1px solid #ddd;
        margin-bottom: 20px;
    }
    .item-box{
        display:flex;
        align-items:center;

        >*{
            margin-right:10px;
        }
    }
    .back-btn{
        padding:30px 0;
        text-align :center;
    }
    .type-item-box{
        padding-bottom 20px;
    }
    .line{
        border-top: 0;
        border-bottom: 1px dashed #ddd;
        margin-bottom:22px;
    }
    .unit-box{
        text-align: center;
        margin-bottom: 22px;
        padding: 0 10px;
    }
    .for-form-box{
        padding: 0 10px;
        padding-top: 20px;
        border-radius: 4px;
        transition: all 0.3s;
        margin-bottom: 10px;

        &:hover{
            background-color:#ecf5ff;
        }
    }
    .error-text{
        color: #f56c6c;
        font-size: 12px;
        padding-bottom: 10px;
        margin-top: -5px;
    }
    .error-bg{
        background: #fef0f0 !important;
    }
}
.posterurl .el-form-item__label:before{
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

</style>
